const express = require('express')
const multer = require('multer')
const path = require('path')
const fs = require('fs')
const { body, query, param, validationResult } = require('express-validator') // 添加 param
const Video = require('../models/video.model')
const { authMiddleware, optionalAuthMiddleware, adminMiddleware } = require('../middlewares/auth.middleware') // 添加 optionalAuthMiddleware
const videoController = require('../controllers/video.controller')
const videoMiddleware = require('../middlewares/video.middleware')
const router = express.Router()
const { updateVideoStatus } = require('../controllers/video.controller');

// 配置视频文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    let uploadDir;
    if (file.fieldname === 'video') {
      uploadDir = path.join(__dirname, '../../uploads/original');
    } else if (file.fieldname === 'thumbnail') {
      uploadDir = path.join(__dirname, '../../uploads/thumbnails');
    }
    // 确保上传目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true })
     }
    cb(null, uploadDir)
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, uniqueSuffix + path.extname(file.originalname))
  }
})

const upload = multer({
  storage,
  limits: {
    fileSize: 500 * 1024 * 1024,
  },
  fileFilter: (req, file, cb) => {
    // 检查是否是视频文件
    if (file.fieldname === 'video') {
      const allowedTypes = [
        'video/mp4',
        'video/webm',
        'video/ogg',
        'video/quicktime', 
        'video/x-msvideo',
        'video/x-ms-wmv',  
        'video/x-matroska', 
        'video/mpeg',       
        'video/3gpp'        
      ]
      if (allowedTypes.includes(file.mimetype)) {
        cb(null, true)
      } else {
        cb(new Error(`不支持的视频格式: ${file.mimetype}。支持的格式: mp4, webm, ogg, mov, avi, wmv, mkv, mpeg, 3gp`))
      }
    }
    // 检查是否是图片文件
    else if (file.fieldname === 'thumbnail') {
      const allowedTypes = [
        'image/jpeg',  
        'image/jpg',   
        'image/png',
        'image/gif',
        'image/webp'
      ]
      if (allowedTypes.includes(file.mimetype)) {
        cb(null, true)
      } else {
        cb(new Error(`不支持的图片格式: ${file.mimetype}。支持的格式: jpg/jpeg, png, gif, webp`))
      }
    }
    // 未知的字段名
    else {
      cb(new Error(`未知的上传字段: ${file.fieldname}`))
    }
  }
})

// 上传视频
router.post('/upload',
  authMiddleware,
  upload.fields([
    { name: 'video', maxCount: 1 },
    { name: 'thumbnail', maxCount: 1 }
  ]),
  [
    body('title').trim().isLength({ min: 2, max: 100 }).withMessage('标题长度必须在2-100个字符之间'),
    body('description').optional().trim().isLength({ max: 5000 }).withMessage('描述不能超过5000个字符'),
    body('category').notEmpty().withMessage('必须选择视频分类'),
    body('tags').optional().custom((value) => {
      try {
        const tags = JSON.parse(value);
        if (!Array.isArray(tags)) throw new Error('标签必须是数组');
        if (tags.length > 10) throw new Error('标签数量不能超过10个');
        return true;
      } catch (e) {
        throw new Error('标签格式无效');
      }
    }),
    body('privacy').isIn(['public', 'unlisted', 'private']).withMessage('无效的隐私设置'),
    body('status').optional().isIn(['pending', 'processing', 'ready', 'failed']).withMessage('无效的状态值')
  ],
  async (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next();
  },
  videoMiddleware.cleanupUpload,
  videoMiddleware.getVideoInfo,
  videoController.uploadVideo
);

// 获取视频列表 (公共/管理员通用)
router.get('/', 
  optionalAuthMiddleware, 
  videoController.getVideos 
);

// 获取推荐视频
router.get('/recommended/list', videoController.getRecommendedVideos)

// 获取热门视频
router.get('/trending/list',
  [
    query('period').optional().isIn(['today', 'week', 'month']).withMessage('无效的时间范围'),
    query('limit').optional().isInt({ min: 1, max: 50 }).withMessage('limit 必须是 1 到 50 之间的整数')
  ],
  async (req, res, next) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() })
    }
    next()
  },
  videoController.getTrendingVideos
)

// 获取最新视频
router.get('/latest/list', // 修正路径
  [
    query('limit').optional().isInt({ min: 1, max: 50 }).withMessage('limit 必须是 1 到 50 之间的整数')
  ],
   async (req, res, next) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() })
    }
    next()
  },
  videoController.getLatestVideos
)

// 根据分类获取视频
// 根据分类获取视频
router.get('/category/:categoryName',
  [
    // 修改分类验证，支持URL编码的分类名
    param('categoryName').custom(value => {
      const decodedValue = decodeURIComponent(value);
      return ['娱乐', '音乐', '游戏', '科技', '教育', '生活', '体育', '新闻', '电影'].includes(decodedValue);
    }).withMessage('无效的分类名称'),
    query('page').optional().isInt({ min: 1 }).withMessage('page 必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 50 }).withMessage('limit 必须是 1 到 50 之间的整数')
  ],
  async (req, res, next) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() })
    }
    next()
  },
  videoController.getVideosByCategory
)

// 搜索视频
router.get('/search',
  [
    query('q').optional().isString().trim(),
    query('page').optional().isInt({ min: 1 }).withMessage('page 必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 50 }).withMessage('limit 必须是 1 到 50 之间的整数'),
    query('sort').optional().isIn(['relevance', 'date', 'views']).withMessage('无效的排序方式'),
    query('time').optional().isIn(['all', 'hour', 'today', 'week', 'month', 'year']).withMessage('无效的时间范围'),
    query('duration').optional().isIn(['any', 'short', 'long']).withMessage('无效的时长选项'),
    query('type').optional().isIn(['all', 'video', 'channel', 'playlist']).withMessage('无效的类型选项')
  ],
  async (req, res, next) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() })
    }
    next()
  },
  videoController.searchVideos
)

// 获取用户订阅的视频列表
router.get('/subscriptions', authMiddleware, videoController.getSubscribedVideos);

// 获取视频处理状态
router.get('/:videoId/status', authMiddleware, videoController.getVideoStatus);

// --- Admin Routes ---

// 新增：管理员获取视频列表
router.get('/admin/list',
  authMiddleware, // 首先确保已登录
  adminMiddleware, // 然后确保是管理员
  videoController.getVideosForAdmin
);

// 管理员更新视频状态 (审核)
router.patch(
  '/admin/videos/:id/status',
  authMiddleware, // 确保用户已登录
  adminMiddleware, // 确保用户是管理员
  [
    body('status', '状态是必需的').notEmpty(), // 使用 body 替代 check
    body('status', '无效的状态').isIn(['pending', 'ready', 'failed', 'rejected']) // 使用 body 替代 check
  ],
  updateVideoStatus // 使用新的控制器方法
);

// 获取相关视频
router.get('/:id/related',
    [param('id').isMongoId().withMessage('无效的视频 ID')],
    async (req, res, next) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }
        next();
    },
    videoController.getRelatedVideos
);

// 添加视频评论路由重定向
router.get('/:id/comments',
  [
    param('id').isMongoId().withMessage('无效的视频ID'),
    query('page').optional().isInt({ min: 1 }).withMessage('page必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 50 }).withMessage('limit必须是1到50之间的整数')
  ],
  async (req, res, next) => {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
      }

      // 构建重定向URL，保留所有查询参数
      const queryString = new URLSearchParams(req.query).toString();
      const redirectUrl = `/api/comments/target/video/${req.params.id}${queryString ? `?${queryString}` : ''}`;
      
      res.redirect(redirectUrl);
    } catch (error) {
      console.error('评论重定向失败:', error);
      res.status(500).json({ error: '评论重定向失败' });
    }
  }
);

// 更新视频信息
router.patch('/:videoId',
  authMiddleware, // 必须登录
  [ // 添加验证
    param('videoId').isMongoId().withMessage('无效的视频 ID'),
    body('title').optional().trim().isLength({ min: 2, max: 100 }).withMessage('标题长度必须在2-100个字符之间'),
    body('description').optional().trim().isLength({ max: 5000 }).withMessage('描述不能超过5000个字符'),
    body('category').optional().notEmpty().withMessage('必须选择视频分类'),
    body('tags').optional().isArray({ max: 10 }).withMessage('标签必须是数组且数量不能超过10个'),
    body('privacy').optional().isIn(['public', 'unlisted', 'private']).withMessage('无效的隐私设置')
  ],
  async (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next();
  },
  // TODO: 添加权限检查中间件 (确保是视频所有者或管理员)
  videoController.updateVideoDetails // 指向控制器处理函数
);

// 删除视频
router.delete('/:videoId',
  authMiddleware, // 必须登录
  [param('videoId').isMongoId().withMessage('无效的视频 ID')],
  async (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next();
  },
  // TODO: 添加权限检查中间件 (确保是视频所有者或管理员)
  videoController.deleteVideo // 指向控制器处理函数
);

// 点赞/取消点赞视频
router.post('/:id/like',
  authMiddleware,
  [param('id').isMongoId().withMessage('无效的视频 ID')],
  async (req, res, next) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() })
    }
    next()
  },
  videoController.likeVideo
);

// 获取视频交互状态
router.get('/:id/interaction',
  optionalAuthMiddleware,
  [param('id').isMongoId().withMessage('无效的视频 ID')],
  async (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next();
  },
  videoController.getVideoInteractionStatus
);

// 获取单个视频详情
router.get('/:videoId',
  optionalAuthMiddleware, // 允许未登录访问，但登录后会附加用户信息
  [param('videoId').isMongoId().withMessage('无效的视频 ID')],
  async (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next();
  },
  videoController.getVideoDetails
);

module.exports = router;